package com.example.jdai.jdai.threeparty;

import android.util.Log;

import com.example.jdai.jdai.MyApplication;
import com.example.jdai.jdai.config.Config;
import com.example.jdai.jdai.rest.GetData;
import com.example.jdai.jdai.rest.RestApi;
import com.example.jdai.jdai.rest.SendCode;
import com.example.jdai.jdai.rest.bean.LoginBean;
import com.example.jdai.jdai.util.Tools;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.KeyGenerator;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.android.storage.persistent.FileRecorder;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Lovepyj on 2016/6/2.
 */
public class FileUploadThread extends Thread {

    String url;
    String newname;
    UploadOptions uploadOptions;
    UpCompletionHandler upCompletionHandler;
    File uploadFile;
    onError onError;
    public FileUploadThread(String url, String newname,UploadOptions uploadOptions, UpCompletionHandler upCompletionHandler,onError onError)
    {
        this.url=url;
        this.newname=newname;
        this.uploadOptions=uploadOptions;
        this.upCompletionHandler=upCompletionHandler;
        this.onError=onError;
    }
    @Override
    public void run() {
        super.run();
        uploadFile = new File(this.url);
        if(!uploadFile.exists())
        {
            if (Config.ISDEBUG)
            Log.v("fileerror","文件不存在");
            onError.error();
            return;
        }

        //Log.v("ssss","kkkk");
        Call call =MyApplication.okClient.newCall(Tools.getRequest(Config.QINIUTOKEN,null));
        call.enqueue(new Callback()
        {
            @Override
            public void onFailure(Call call, IOException e) {

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String bd=response.body().string();
                if (Config.ISDEBUG)
                    Log.v("qiniu",bd );
                GetData<String> token=new Gson().fromJson(bd,new TypeToken<GetData<String>>(){}.getType());
                upload(token.getData());
            }

        });
//        RestApi.TokenService service = MyApplication.retrofit.create(RestApi.TokenService.class);
//        SendCode send=new SendCode();
//        service.getToken(RestApi.getBody(send))
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Subscriber<GetData<String>>() {
//                    @Override
//                    public void onCompleted() {
//
//                    }
//                    @Override
//                    public void onError(Throwable e) {
//                        //Log.v("errof",e.toString());
//
//                    }
//                    @Override
//                    public void onNext(GetData<String> stringStringMap) {
//
//                        //Log.v( "sss",stringStringMap.getData());
//                        //stringStringMap.code();
//                        upload(stringStringMap.getData());
//                    }
//                });





//        final OkHttpClient httpClient =new OkHttpClient();
//        Request req = new Request.Builder().url(Config.QINIUTOKEN).build();
//        Response resp = null;
//        try {
//            resp = httpClient.newCall(req).execute();
//            String key=resp.body().string();
//            Log.v("key",key);
//            upload(key);
//        } catch (IOException e) {
//            //e.printStackTrace();
//            Log.v("neterror","网络错误");
//        }
    }

    private void upload(String uploadToken) {

        UploadManager uploadManager = null;
//        try {
//            uploadManager = new UploadManager(new FileRecorder(
//                                MyApplication.applicationContext.getFilesDir() + "/QiniuAndroid"),
//                                new KeyGenerator() {
//                                    // 指定一个进度文件名，用文件路径和最后修改时间做hash
//                                    // generator
//                                    @Override
//                                    public String gen(String key, File file) {
//                                        String recorderName = System.currentTimeMillis() + ".progress";
//                                        //recorderName = "nihao";
//                                        return "niahao1";
//                                    }
//                                });
//            //Configuration config = new Configuration.Builder().zone(Zone.httpAutoZone).build();
//            //uploadManager = new UploadManager(config);
//        } catch (IOException e) {
//           // e.printStackTrace();
//            if (Config.ISDEBUG)
//            Log.v("um","出现错误");
//            return;
//        }
        Configuration config = new Configuration.Builder().zone(Zone.httpAutoZone).build();
        uploadManager = new UploadManager(config);
        if(uploadOptions==null)
        {
            uploadOptions = new UploadOptions(null, null, false,
                    new UpProgressHandler() {
                        @Override
                        public void progress(String key, double percent) {
                            if (Config.ISDEBUG)
                            Log.v("jindu",percent+"");
                        }
                    }, new UpCancellationSignal() {

                @Override
                public boolean isCancelled() {
                    return false;
                }
            });
        }
        if (upCompletionHandler==null)
        {
            upCompletionHandler=new UpCompletionHandler() {
                @Override
                public void complete(String key, ResponseInfo info, JSONObject response) {
                    //Log.v("ok","ok");
                }
            };
        }
//        UploadOptions uploadOptions = new UploadOptions(null, null, false,
//                new UpProgressHandler() {
//                    @Override
//                    public void progress(String key, double percent) {
//                        Log.v("jindu",percent+"");
//                    }
//                }, new UpCancellationSignal() {
//
//            @Override
//            public boolean isCancelled() {
//                return cancelUpload;
//            }
//        });

        uploadManager.put(uploadFile, newname, uploadToken,upCompletionHandler, uploadOptions);

    }
    public interface onError{
        void error();
    }

}
